<template>
  <div class="login">
    <van-nav-bar
  title="标题"
  left-arrow
  @click-left="$router.back()"
/>
<van-form @submit="login">
  <van-field
    v-model="mobile"
    label="手机号"
    placeholder="请输入您的手机号"
    :rules="rules.mobile"
  />
  <van-field
    v-model="code"
    label="验证码"
    placeholder="请输入您的验证码"
    :rules="rules.code"
  />
  <div style="margin: 16px;">
    <van-button round block type="info" native-type="submit" :disabled="loading" :loading="loading" loading-text="登陆中...">登录</van-button>
  </div>
</van-form>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      mobile: '13912345678',
      code: '246810',
      loading: false,
      rules: {
        mobile: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式错误'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async login () {
      this.loading = true
      try {
        const res = await login(this.mobile, this.code)
        console.log(res)
        // this.$store.commit('user/setToken', res.data)
        this.setToken(res.data)
        this.$toast.success('登陆成功')
        this.$router.push('/')
      } catch {
        this.$toast.fail('登录失败')
      }
      this.loading = false
    }
  }
}
</script>

<style>
.van-button {
 background-color: #1a6840 !important;
 border: #1a6840 !important;
}
</style>
